#!/usr/bin/env python3
# coding: utf-8
"""
2024-02-18 vos
"""

import datetime
import json
from top.wardyan.core.utils.common import *

class Record :
    """类似jfinal里的Record

    Args:
        dict (_type_): _description_
    """
    ##_data_ : dict = {}



    def __init__(self) :
        self.setData({})
    # def __init__(self, data : dict = {}) :
    #     self.setData(data)

    

    def __check_key__(self, key : str) -> str :
        """初始化检查key

        Args:
            key (str): _description_

        Returns:
            str: _description_
        """
        if key is None :
            key = ""
        return key

    def setData(self, data : dict = {}) :
        if data is None :
            data = {}
        self._data_ = data

    def set(self, key : str, value) :
        key = self.__check_key__(key = key)
        self._data_[key] = value
        ## print(self._data_, key, value)

    def remove(self, key : str):
        rs = None
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            rs = self._data_[key]
            del self._data_[key]
        return rs

    def clear(self) :
        self._data_.clear()
        ## self._data_ = {}

    def get(self, key : str) :
        rs = None
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            rs = self._data_[key]
        return rs

    def getStr(self, key : str) -> str:
        """
        默认返回值到底应该是None还是""?
        """
        rs = ""
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            ## rs = self._data_[key]
            r = self._data_[key]
            if type(r) is str :
                rs = r
            else :
                rs = str(r)
        return rs

    
    def getInt(self, key : str) -> int:
        rs = 0
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            r = self._data_[key]
            if type(r) is int :
                rs = r
            else :
                rs = int(r)
        return rs

    
    def getFloat(self, key : str) -> float:
        rs = 0.0
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            r = self._data_[key]
            if type(r) is float :
                rs = r
            else :
                rs = float(r)
        return rs

    
    def getBool(self, key : str) -> bool:
        rs : bool = None
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            r = self._data_[key]
            if type(r) is bool :
                rs = r
            else :
                s : str = str(r)
                if s is None :
                    s = ""
                s = s.lower()
                rs = ( "true" == s )
        return rs

    def getTimestamp(self, key : str) -> str :
        """
        读取日期时间并以字符串格式返回, 格式: yyyy-MM-dd HH:mm:ss.fff
        """
        rs = None
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            r = self._data_[key]
            if  r is not None and type(r) == datetime.datetime:
                rs = formatdatetime(r)
        return rs

    def getDateTime(self, key : str) -> datetime.datetime:
        rs : datetime.datetime = None
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            r = self._data_[key]
            if r is not None and  type(r) == datetime.datetime :
                rs = r
        return rs

    def getMillisecond(self, key : str) -> int :
        """
        读取日期时间并以毫秒返回
        """
        rs : int = 0
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            r : datetime.datetime = self._data_[key]
            if  r is not None and type(r) == datetime.datetime :
                rs = int(r.timestamp() * 1000)
        return rs

    def keys(self) -> list[str]:
        return list(self._data_.keys())

    def containKey(self, key : str) -> bool :
        rs : bool = False
        key = self.__check_key__(key = key)
        if key in self._data_.keys() :
            rs = True
        return rs

    def getIdx(self, idx : int) :
        rs = None
        if idx is None or idx < 0 : 
            return rs

        keys = self.keys()
        cnt = len(keys)
        if idx > cnt - 1 :
            return rs

        key = keys[idx]
        rs = self.get(key=key)
        return rs

    def todict(self) :
        rs = {}
        for key in self.keys() :
            value = self.get(key)
            rs[key] = value
        return rs
    def as_dict(self):
        return self.todict()
    
    def datetime_handler(self, x):
        if isinstance(x, datetime.datetime):
            return x.isoformat()
        raise TypeError("Unknown type")
    def tojsonstr(self) :
        #rs = str(self.todict())
        rs = json.dumps(self.todict(), default=self.datetime_handler, ensure_ascii=False)
        return rs

def recordstodicts(datas : list[Record]) -> list[dict]:
    rs = []
    if datas is None :
        datas = []
    for data in datas :
        d : dict = data.todict()
        rs.append(d)
    return rs

def recordstojsonsr(datas : list[Record]) -> str :
    return str(recordstodicts(datas))

def dicttorecord(data : dict)  -> Record :
    rs : Record = Record()
    if data is None :
        data = {}
    for key in data.keys()  :
        value = data.get(key)
        rs.set(key, value)
    return rs

    

def jsonstrtorecord(jsonstr : str) -> Record:
    #rs : Record = None
    ds : dict = json.loads(jsonstr)
    return dicttorecord(ds)

def listtorecords(datas : list[dict]) -> list[Record]:
    rs : list[Record] = []
    if datas is None :
        datas = []
    for data in datas :
        r = dicttorecord(data)
        rs.append(r)
    return rs

def jsonstrtorecorfds(jsonstr : str) -> list[Record] :
    js = json.loads(jsonstr, object_pairs_hook=dicttorecord)
    ds : list[dict] = list(js)
    return listtorecords(ds)



class TableColCfg :

    def __init__(self) -> None:

        self.id : int = 0
        self.tableID : int = 0

        ## 字段名
        self.field : str = ""
        ## 标题
        self.title : str = ""
        ## 对齐方式
        self.align : int = 0
        ## 列宽
        self.width : int = 0
        ## 是否显示
        self.show : bool = True
        ## 替换显示值
        self.replace : str = ""
        ## 数据类型
        self.datatype : int = 0
        ## 格式化
        self.format : str = ""

        ## 固定替换值
        ## replaces : list[str]
        self._replaces : dict[str,str] = {}

        ## SQL替换值
        self.sql : str = ""

        self.idx : int = 0
        self.dicID : int = 0



    

class TableCfg :
    """
    表格配置
    """

    def __init__(self) -> None:
        # widgetname : str = ""
        # tablename : str = ""
        self.id : int = 0
        self.winID : int = 0
        
        ## 名称
        self.name : str = ""
        ## 字段列表, 所有的
        self.fields : list[str] = []
        ## 行高
        self.height : int = 30
        ## 每一个列的情况
        self.cols : list[TableColCfg] = []
        
        self.rowcolor = False
        
        ## 列是否允许拖拽
        self.colmoveable = False
    
    def getColCfg(self, field : str) -> TableColCfg:
        rs : TableColCfg = None
        for col in self.cols :
            if col.field == field :
                rs = col
                break
        return rs


        
    def getColCfgs(self) -> dict[str,TableColCfg]:
        rs : dict[str,TableColCfg] = {}
        for col in self.cols :
            rs[col.field] = col
        return rs


    ## def __init__(self, widgetname : str, tablename : str) -> None:
    # def __init__(self) -> None:
    #     self.widgetname = widgetname
    #     self.tablename = tablename
    #     self.readcfg()

    # def readcfg(self) :
    #     """读取配置
    #     """
    #     pass

class WinCfg :
    ## TableCfg
    def __init__(self) -> None:
        self.id : int = 0
        self.name : str = "default"
        self.title : str = "开发辅助工具 © harrydeep@wardyan.top 2024-06-20"
        self.isFullScreen : bool = True
        self.x : int = 800
        self.y : int = 600
        self.width : int = 0
        self.height : int = 0
        self.isMoveable : bool = True
        self.position : int = 0
        self.icon = ""
        self.tables : list[TableCfg] = []


if __name__ == "__main__" :
    
    r = Record({"xDateTime":datetime.datetime.now(),"name":"hello"})
    print(r.getTimestamp("xDateTime"))
    print(r.getDateTime("xDateTime"))
    print(r.getMillisecond("xDateTime"))
    print(r.keys())
    print(r.getIdx(0),r.getIdx(1),r.getIdx(2))

    